import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import libsvm.*;


public class EmoDetect_m3_speech {

	public static HashSet<String> stopwords = new HashSet<String>();//停用词（包括英文字母)
	public static HashSet<String> senti = new HashSet<String>();//情感词典
	public static HashSet<String> angrylist = new HashSet<String>();//情感词典
	public static HashMap<Integer,String> test = new HashMap<Integer,String>();//将过滤到路径信息的文本写入test
	public static HashMap<Integer,String> svmtest = new HashMap<Integer,String>();//存放svmtest特征文本
	public static List<String> result = new ArrayList<String>();//存放result
	public static List<String> resultlist = new ArrayList<String>();//存放result+sen;送入规则处理
	public static List<String> newresultlist = new ArrayList<String>();//规则处理后的结果
	public static List<String> revise_newresultlist = new ArrayList<String>();
	public static List<String> speechresultlist = new ArrayList<String>();
	public static List<String> txt_speech_result = new ArrayList<String>();
	public static List<String> revise_txt_speech_result = new ArrayList<String>();
	public static HashMap<Integer,String> fea_senti = new HashMap<Integer,String>();
	public static HashMap<String, Double> gramIDF= new HashMap<String, Double>(); //存放所有gram和gram2的IDF
	public static HashMap<String, Integer> gramIndex= new HashMap<String, Integer>(); //存放所有gram和gram2和其index	
	public static HashMap<String, Double> txt_result = new HashMap<String, Double>(); 
	public static HashMap<Integer,String> indexFile = new HashMap<Integer,String>();//将过滤到路径信息的文本写入test
	public static HashMap<String,List<String>> txtresultmap = new HashMap<String,List<String>>();
	public static HashMap<String,List<String>> speechresultmap = new HashMap<String,List<String>>();
	public static HashMap<String,List<String>> combineresultmap = new HashMap<String,List<String>>();
	public static HashMap<String,List<String>> revise_txtresultmap = new HashMap<String,List<String>>();//根据对话结果修改标注后的结果
	public static HashMap<String,List<String>> revise_combineresultmap = new HashMap<String,List<String>>();
	
	DecimalFormat fnum = new DecimalFormat("##0.000"); //保留三位小数
	
	//定义配置文件参数
	public static Integer dialength;
	public static Double emotionths1;
	public static Double emotionths2;
	
	//读取配置文件信息
	public static void getConfig() {
		
		Properties property = new Properties();
		try {			
			property.load(new FileInputStream("config.properties"));
			dialength = Integer.valueOf(property.getProperty("dialength"));
			emotionths1 = Double.valueOf(property.getProperty("emotionths1"));
			emotionths2 = Double.valueOf(property.getProperty("emotionths2"));		
		} catch (Exception e) {
			System.err.println("Loading configuration failed, please check.");
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	public void readDic() throws Exception{//生成stopwords, senti, gramIDF, gramIndex, gram2IDF，gram2Index
		
		InputStreamReader read = new InputStreamReader(new FileInputStream("dictionary_g1_g2_senti"),"utf-8");
		BufferedReader reader = new BufferedReader(read);
		String temp ="";
		while((temp = reader.readLine()) != null){
			String[] tokens = temp.split("\t");
			String cate = tokens[0];
			String item = tokens[1];
			switch(cate){
				case "st"://代表停用词
					stopwords.add(item);
					break;
				case "se"://代表情感词
					senti.add(item);
					break;
				case "g":
					String[] gramtokens = item.split(" ");
					Integer index = Integer.valueOf(gramtokens[0]);
					String gram = gramtokens[1];
					Double gramidf = Double.valueOf(gramtokens[2]);
					gramIDF.put(gram, gramidf);
					gramIndex.put(gram, index);
					break;
			}
		}
		reader.close();
	}
	
	public String getSentiFea(String line) throws Exception{
		
		String feasenti = "";
		for(String sentiline : senti){
			String[] tokens = sentiline.split(" ");
			String index = tokens[0];
			String lex = tokens[1];
			String value = tokens[2];
			if(line.contains(lex)){
				feasenti = feasenti + index + ":" + value + " ";
			}
		}
		return feasenti;
	}
	
	public void readFile(String file) throws Exception{//读取文本，同时获取角色、情感特征
		
		InputStreamReader read = new InputStreamReader(new FileInputStream(file),"gbk");
		BufferedReader reader = new BufferedReader(read);
		String testtemp = "";
		String content = "";
		String senti = "";
		int index = 0;
		while((testtemp = reader.readLine()) != null){			
			if (testtemp.substring(0, 1).contains("/")){//过滤路径行
				continue;
			}
			String[] tokens = testtemp.split("	");
			content = tokens[2];	
			senti = getSentiFea(content);
			test.put(index, content);	
			fea_senti.put(index, senti);
			index += 1;						
		}
		reader.close();
	}
	
	public void FormateData() throws IOException{		
		
		String content = "";
		int index = 0;
		Iterator<Integer> iter = test.keySet().iterator();
		while (iter.hasNext()) {
			index = iter.next();
			content = test.get(index);
			HashMap<String, Integer> gramMap = new HashMap<String, Integer>();//gramMap存放每句话的gram和gram2信息			
			for(int i= 0; i<content.length()-1; i++){
				String gram = content.substring(i, i+1);
				if(stopwords.contains(gram)==false && gram.length()>0 && gram.trim().isEmpty()==false){
					if(gramMap.containsKey(gram)){
						gramMap.put(gram, gramMap.get(gram)+1);
					}else{
						gramMap.put(gram, 1);
					}
				}
				String gram2 = content.substring(i, i+2);//word为2gram
				if(stopwords.contains(gram2)==false && gram2.length()>0 && gram2.trim().isEmpty()==false){
					if(gramMap.containsKey(gram2)){
						gramMap.put(gram2, gramMap.get(gram2)+1);
					}else{
						gramMap.put(gram2, 1);
					}			
				}
			}			
			HashMap<Integer, Double> gramTfIdf = new HashMap<Integer, Double>();
			Iterator<String> grammap = gramMap.keySet().iterator();
			while(grammap.hasNext()){
				String gram = grammap.next();
				if(gramIndex.containsKey(gram) && gramIDF.containsKey(gram)){
					double tf = (double)(gramMap.get(gram)) / (content.length() - 1);
					double idf = gramIDF.get(gram);
					double tfidf = tf * idf ;
					gramTfIdf.put(gramIndex.get(gram), tfidf);
				}
			}
			String fea_word = "";
		    Object[] key =  gramTfIdf.keySet().toArray();
		    Arrays.sort(key); 
		    for(int i = 0; i<key.length; i++)  {    
		    	fea_word = fea_word +  String.valueOf(key[i]) + ":" +  String.valueOf(gramTfIdf.get(key[i])) + " ";    		    	
		    } 
//			System.out.println(fea_word);
//		    String fea_all = fea_role.get(index) + " " + fea_senti.get(index) + fea_word;
		    String fea_all = fea_senti.get(index) + fea_word;
		    svmtest.put(index, fea_all);
		}
//		System.out.println("Feature Completed. ");
	}
	
	public String predict(String line, svm_model model, int predict_probability) throws IOException{
		
		String output = "";
		int svm_type=svm.svm_get_svm_type(model);
		int nr_class=svm.svm_get_nr_class(model);
		double[] prob_estimates=null;
		
		if(predict_probability == 1){
			int[] labels=new int[nr_class];
			svm.svm_get_labels(model,labels);
			prob_estimates = new double[nr_class];
		}
		
		StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
		
		int m = st.countTokens()/2;
		svm_node[] x = new svm_node[m];
		for(int j=0;j<m;j++){
			x[j] = new svm_node();
			x[j].index = Integer.parseInt(st.nextToken());
			x[j].value = Double.valueOf(st.nextToken()).doubleValue();
		}
		
		double v;
		if (predict_probability==1 && (svm_type==svm_parameter.C_SVC || svm_type==svm_parameter.NU_SVC)){
			v = svm.svm_predict_probability(model,x,prob_estimates);
			output = v+" ";
			for(int j=0;j<nr_class;j++)
				output= output + prob_estimates[j]+" ";
		}else{
			v = svm.svm_predict(model,x);
			output= v+"\n";
		}		
		return output;
	}
	
	public List<String> multipredict(List<Map.Entry<Integer, String>> list, Integer treadcount) throws Exception{
		
		final svm_model model = svm.svm_load_model("model_g1_g2_senti");
		HashMap<Integer, String> resultTemp = new HashMap<Integer, String>();//存放预测结果
		List<String> resultLs = new ArrayList<String>();//存放预测结果
		    
		int threadCounts = treadcount;//此处定义使用的线程数  
		ExecutorService exec=Executors.newFixedThreadPool(threadCounts);//根据定义的线程数目进行开辟线程
		List<Callable<HashMap<Integer,String>>> callList=new ArrayList<Callable<HashMap<Integer,String>>>();//生成很大的List
		
		int len=list.size()/threadCounts;//根据线程数目，平均分割List，这是每段sublist的大小		
		if(len==0){//List中的数量没有线程数多（很少存在）
			threadCounts=list.size();//采用一个线程处理List中的一个元素
			len=list.size()/threadCounts;//重新平均分割List
		}//此处是为了防止线程数目大于list的大小，可不用管
		for(int i=0;i<threadCounts;i++){//这个for循环是为了启动各个线程，并且定义每个线程要处理的内容						
			final List<Entry<Integer, String>> subList;
			if(i==threadCounts-1){
				subList=list.subList(i*len,list.size());
			}else{
				subList=list.subList(i*len, len*(i+1)>list.size()?list.size():len*(i+1));
			}//此处if-else是为了在for循环中均分前面定义的list
			callList.add(new Callable<HashMap<Integer,String>>(){
				public HashMap<Integer,String> call() throws Exception {
//					List<Entry<Integer, String>> alist = new ArrayList<Entry<Integer, String>>();
					HashMap<Integer,String> alistMap = new HashMap<Integer, String>();
					for(Entry<Integer, String> i:subList){
						int index = i.getKey();
						String line = i.getValue();
						alistMap.put(index, predict(line, model, 1));//对每一句话进行预测
					}
					return alistMap;//此处将上述处理得到的结果进行返回，并保存到callList中
				}
			});
		}
		//等待所有的for循环处理完毕，将每个线程中的结果集合进行汇总
		List<Future<HashMap<Integer, String>>> futureList=exec.invokeAll(callList);
		for(Future<HashMap<Integer, String>> future:futureList){
			resultTemp.putAll(future.get());
		}		
		Object[] key =  resultTemp.keySet().toArray();//将结果进行排序，以免组合sublist时乱序
		Arrays.sort(key); 
	    for(int i = 0; i<key.length; i++)  {    
	    	resultLs.add(resultTemp.get(key[i])); 
//	    	System.out.println(resultTemp.get(key[i]));
	    }		
		exec.shutdown();//结束线程集合
		
		return resultLs;
	}
	
	public void Predict(Integer treadcount) throws Exception{	
			
		List<Map.Entry<Integer, String>> svmtestList = new ArrayList<Map.Entry<Integer, String>>(svmtest.entrySet());
		result = multipredict(svmtestList, treadcount);	
	}
		
	public void conbineTxtResult(String path) throws Exception{		
		
		InputStreamReader read = new InputStreamReader(new FileInputStream(path),"gbk");
		BufferedReader reader = new BufferedReader(read);
		String testtemp = "";
		int i = 0;
		while((testtemp = reader.readLine()) != null){	
			if (testtemp.substring(0, 1).contains("/")){
			resultlist.add(testtemp + '\n');
			continue;
			}
			String re = result.get(i);
			double P1 = Double.valueOf(re.split(" ")[1]);
			double P2 = Double.valueOf(re.split(" ")[2]);
			String lable = re.split(" ")[0];
			switch(lable){
			case "0.0":	
				resultlist.add(testtemp + "\t" + "[Angry]" +"\t" + fnum.format(P1) + "\n");
				break;
			case "1.0":
				resultlist.add(testtemp + "\t" + "[Neu]" +"\t" + fnum.format(P2) + "\n");
				break;
			}
			i = i + 1;
		}	
		reader.close();	
	}

	public String processLingRule(String[] tokens, String cateStr, String scoreStr) {

		String tempStr = "";
		for(int k=0; k<tokens.length; k++){
			String temp = tokens[k];;
			if(k==4) temp = cateStr;
			if(k==5) temp = scoreStr;
			tempStr += temp + "\t";
		}
		String newresultstring = tempStr.trim() + "\n";
		return newresultstring;

	}

	public void addLingRule(String outpath) throws IOException {//加入语言规则
		
		File file = new File(outpath);
		Writer writer = new OutputStreamWriter(new FileOutputStream(file),"gbk");//将结果写入指定路径
		
		for(int i=0; i<resultlist.size(); i++){
			String newresultstring = resultlist.get(i);
			//规则1：凡是坐席说的“投诉”，词句均判断为中性
			if(resultlist.get(i).contains("投诉") && resultlist.get(i).contains("	坐席")){
				String[] tokens = resultlist.get(i).split("\t");
				newresultstring = processLingRule(tokens, "[Neu]", "0.999");
			}
			//规则2：若是坐席被判断为Angry，但其的概率小于0.9，则将其强行改为中性
			if (resultlist.get(i).contains("	[Angry]") && resultlist.get(i).contains("	坐席") && Float.valueOf(resultlist.get(i).split("\t")[5])< 0.98) {
				String[] tokens = resultlist.get(i).split("\t");
				newresultstring = processLingRule(tokens, "[Neu]", "0.499");
			}
			//规则3：若Angry的值小于0.9，则强行改为中性。
			if (resultlist.get(i).contains("	[Angry]") && Float.valueOf(resultlist.get(i).split("\t")[5]) < 0.9) {
				String[] tokens = resultlist.get(i).split("\t");
				newresultstring = processLingRule(tokens, "[Neu]", "0.499");
			}
			//规则4：凡是客户说的“投诉”，词句均判断为负面
			if(resultlist.get(i).contains("投诉") && resultlist.get(i).contains("	客户")){
				String[] tokens = resultlist.get(i).split("\t");
				newresultstring = processLingRule(tokens, "[Angry]", "0.999");
			}
			//规则5：若话语长度小于5而被判为Angry的，则强行改为中性。
			if (resultlist.get(i).contains("	[Angry]") && resultlist.get(i).split("\t")[2].length()<=6) {
				String[] tokens = resultlist.get(i).split("\t");			
				newresultstring = processLingRule(tokens, "[Neu]", "0.499");
			}
			newresultlist.add(newresultstring);
			writer.write(newresultstring);
		}
		writer.close();
	}
	
	public void produceTxtResult(Integer treadcount, String path, String txtresult) throws Exception {
		
		readDic();
		readFile(path);
		FormateData();             
		Predict(treadcount);
		conbineTxtResult(path);
		addLingRule(txtresult);       //加入语言规则
	}
	
	//声学层结果融合部分
	public void getSpeechResult(String speechresult) throws IOException {
		
		InputStreamReader read = new InputStreamReader(new FileInputStream(speechresult),"gbk");
		BufferedReader reader = new BufferedReader(read);
		String temp = "";				
		while((temp = reader.readLine()) != null) {	
			speechresultlist.add(temp + '\n');
		}
		reader.close();	
	}
	
	//将result文档组织成map的形式，便于之后speech获得相应的结果
	public HashMap<String,List<String>> getResultMap(List<String> resultlist) throws IOException {
		
		HashMap<String,List<String>> resultmap = new HashMap<String,List<String>>();
		List<Integer> wavname_ls = new ArrayList<Integer>();
		for (int i=0; i<resultlist.size(); i++) {			
			if (resultlist.get(i).substring(0, 1).contains("/")){
				wavname_ls.add(i);								
			} 
		}
		for(int j=0; j< wavname_ls.size(); j++) {
			int start, end = 0;
			start = wavname_ls.get(j);
			if (j == wavname_ls.size()-1) {
				end = resultlist.size();
			}else{
				end = wavname_ls.get(j+1);
			}
			Integer dialogue_len = end-start-1; 
			List<String> score_ls = new ArrayList<String>();
			if (dialogue_len > 0) {
				for(int k= start+1; k<end; k++){
					String score = resultlist.get(k);
					score_ls.add(score);
				}
			}
			resultmap.put(resultlist.get(start), score_ls);
//			System.out.println(start);
		}
		return resultmap;
	}
	
	public void combineSpeechResult() throws IOException {
		
		txtresultmap = getResultMap(newresultlist);
		speechresultmap = getResultMap(speechresultlist);
		
		for(int i=0; i<newresultlist.size(); i++){
			if (newresultlist.get(i).substring(0, 1).contains("/")) {
				String wavid = newresultlist.get(i);
				if (speechresultmap.containsKey(wavid) && speechresultmap.get(wavid).size()==txtresultmap.get(wavid).size()) {//如果声学层有此wav的完整结果
					List<String> label_combine_list = new ArrayList<String>();
					for (int j=0; j<speechresultmap.get(wavid).size(); j++) {
						String label_score_speech = speechresultmap.get(wavid).get(j);
						String label_score_txt = txtresultmap.get(wavid).get(j);
//						String sentence = label_score_txt.split("\t")[2];
						float score = Float.valueOf(label_score_txt.split("\t")[5]);
						String label = label_score_txt.split("\t")[4];
						String label_combine = label_score_speech;
						if ((score>0.95) &&(label.contains("Angry"))){//坐席不再是单独读取文本分数，而是和客户一样综合判断
//						if (label_score_speech.contains("	坐席") || (score>0.95) &&(label.contains("Angry"))){
							String[] tokens = label_combine.split("\t");
							String new_label_combine = "";
							for(int k=0; k<tokens.length; k++){
								String temp = tokens[k];;
								if(k==4) temp = "[Angry]";
								if(k==5) temp = String.valueOf(score);
								new_label_combine += temp + "\t";
							}

							label_combine = new_label_combine.trim()+"\n";
						}
						label_combine_list.add(label_combine);
					}
					combineresultmap.put(newresultlist.get(i), label_combine_list);
				} else {//只获取语言层结果
					combineresultmap.put(newresultlist.get(i), txtresultmap.get(newresultlist.get(i)));
				}
			}			
		}		
	}
	
	//将融合后的结果写入txt_speech_result,Map→List
	public List<String> mapTolist(HashMap<String,List<String>> resultmap){
		
		List<String> resultls = new ArrayList<String>();
		for(int i=0; i<newresultlist.size(); i++){
			if (newresultlist.get(i).substring(0, 1).contains("/")) {
				resultls.add(newresultlist.get(i));
				for (int j=0; j<resultmap.get(newresultlist.get(i)).size(); j++) {	
					String label_score_txt = resultmap.get(newresultlist.get(i)).get(j);
					resultls.add(label_score_txt);
					}
				}			
			}
		return resultls;
		}
		
	//基于segment结果得到dialogue结果
	public HashSet<String> dialogue_score(String dia_outpath, List<String> resultlist) throws Exception {
		
		//获取配置文件信息
		getConfig(); 		
		
		File tetsfile = new File(dia_outpath);
		Writer testwriter = new OutputStreamWriter(new FileOutputStream(tetsfile),"gbk");//将结果写入指定路径
		HashSet<String> angrylist = new HashSet<String>();
		
		List<Integer> wavname_ls = new ArrayList<Integer>();
		for (int i=0; i<resultlist.size(); i++) {			
			if (resultlist.get(i).substring(0, 1).contains("/")){
				wavname_ls.add(i);								
			} 
		}
		for(int j=0; j< wavname_ls.size(); j++) {//0418revise;old:wavname_ls.size()-1
			int start, end = 0;
			start = wavname_ls.get(j);
			if (j == wavname_ls.size()-1) {
				end = resultlist.size();
			}else{
				end = wavname_ls.get(j+1);
			}
			float count = 0;
			for(int k= start+1; k<end; k++){
				String label = resultlist.get(k).split("\t")[4];
				if (label.contains("Angry")){
					count += 1;
//					System.out.println(resultlist.get(k));
				}
			}
			Integer dialogue_len = end-start-1;
			if (dialogue_len > 0) {
				float dia_score = count/dialogue_len;//是情绪值。不能简单等于置信度。
/*				System.out.println(count);
				System.out.println(dialogue_len);*/
				//当句长大于某一值时，阈值为A
				if (dialogue_len > dialength) { //阈值1
					if (dia_score > emotionths1) {
		//				System.out.println(txt_speech_result.get(start).trim() + '\t' + "Angry");
						testwriter.write(resultlist.get(start).trim() + '\t' + "Angry" + '\t' + String.valueOf(dia_score) + "\n");
						angrylist.add(resultlist.get(start));					
					}				
				}//当句长小于某一值时，阈值为B
				else {
					if (dia_score > emotionths2) { //阈值2
		//				System.out.println(txt_speech_result.get(start).trim() + '\t' + "Angry");
						testwriter.write(resultlist.get(start).trim() + '\t' + "Angry" + '\t' + String.valueOf(dia_score) + "\n");
						angrylist.add(resultlist.get(start));					
					}
				}
			}
		}
		testwriter.close();
		return angrylist;
	}
	
	public HashMap<String,List<String>> revise_result(HashMap<String,List<String>> resultmap, HashSet<String> angrylist) {//返回可以直接写结果的list
		
		for(int i=0; i<newresultlist.size(); i++){
			if (newresultlist.get(i).substring(0, 1).contains("/")) {
				String wavid = newresultlist.get(i);
				if (angrylist.contains(wavid)==false) {   //修改：Angry→Neu
					List<String> resultls = new ArrayList<String>();
					for (int q=0; q<resultmap.get(wavid).size(); q++) {
						String newline = resultmap.get(wavid).get(q).replace("Angry", "Neu");
						resultls.add(newline);
					}
					resultmap.put(wavid, resultls);
				}
			}
		}			
		return resultmap;
	}
	
	public void writeResult(List<String> resultlist, String outpath) throws Exception{
		
		File tetsfile = new File(outpath);
		Writer testwriter = new OutputStreamWriter(new FileOutputStream(tetsfile),"gbk");//将结果写入指定路径
		
		for(int i=0; i<resultlist.size(); i++){
			testwriter.write(resultlist.get(i));
		}
		testwriter.close();	
	}
	
	public void produceCombineResult(String speechresult, String diaoutput, String outpath) throws Exception {
		
		getSpeechResult(speechresult);
		combineSpeechResult();
		txt_speech_result = mapTolist(combineresultmap);
		writeResult(txt_speech_result, "temp_seg.log");//将修改前的结果写入临时文件
		angrylist = dialogue_score(diaoutput,txt_speech_result);
		revise_combineresultmap = revise_result(combineresultmap, angrylist);
		revise_txt_speech_result = mapTolist(revise_combineresultmap);
		writeResult(revise_txt_speech_result, outpath);				
	}
	
	public void produceFinalTxtResult(String diaoutput, String outpath) throws Exception {
		
		txtresultmap = getResultMap(newresultlist);
		writeResult(newresultlist, "temp_seg.log");	//将修改前的结果写入临时文件
		angrylist = dialogue_score(diaoutput, newresultlist);
		revise_txtresultmap = revise_result(txtresultmap, angrylist);
		revise_newresultlist = mapTolist(revise_txtresultmap);
		writeResult(revise_newresultlist, outpath);					
	}

	public void emotionDetect(Integer treadcount, String path, String speechresult, String txtresult, String outpath, String diaoutput) throws Exception{

		produceTxtResult(treadcount, path, txtresult);
		produceCombineResult(speechresult, diaoutput, outpath);
	}
	
	public void emotionDetect_only_txt(Integer treadcount, String path, String speechresult, String txtresult, String outpath, String diaoutput) throws Exception{
		
		produceTxtResult(treadcount, path, txtresult);
		produceFinalTxtResult(diaoutput, outpath);
	}
	
	public String isExist(String path) {  
		File file = new File(path);  
		if (!file.exists()) { //判断文件是否存在  
			return "0";
		} else if (file.length() < 1.0) {//文件虽然存在，但是大小为空。
			return "0";
		}else {
			return "1";
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub	
		long starttime = System.currentTimeMillis();
		Integer threadcount = Integer.parseInt(args[0]);
		String data_input = args[1];
		String speechresult = args[2];
		String txtresult = args[3];
		String outputseg = args[4];
		String outputdia = args[5];
/*		Integer threadcount = 2;
		String data_input = "text_role_result.txt";
		String speechresult = "speech_emo_result.txt";
		String txtresult = "test_txt_emotion.txt";
		String outputseg = "output_segment_emotion.txt";
		String outputdia = "output_dialogue_emotion.txt";*/
		EmoDetect_m3_speech ed = new EmoDetect_m3_speech();		
		try {
			String speechtxt = ed.isExist(speechresult);
			switch(speechtxt){
			case "0":	
				System.err.println("Warning: speech txt doesn't exist or the txt is empty. The result only from txt system.");
				ed.emotionDetect_only_txt(threadcount,data_input,speechresult,txtresult,outputseg,outputdia);
				break;
			case "1":
				try{
					ed.emotionDetect(threadcount,data_input,speechresult,txtresult,outputseg,outputdia);
					break;
				}catch (Exception e){//若speech文本存在，但其格式出现问题，在融合过程中combineSpeechResult(speechresult)出现异常时，只需要在文本结果基础上计算对话结果。
					System.err.println("Warning: speech txt isn't normal. The result only from txt system.");
					ed.produceFinalTxtResult(outputdia, outputseg);
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		long endtime = System.currentTimeMillis();
		System.err.println(endtime - starttime);
	}
}